package org.paradigmshift.timelapse.rest

import scala.actors.Actor
import org.paradigmshift.timelapse.exceptions.TimeLapseException
import sun.misc.BASE64Encoder
import org.paradigmshift.timelapse.actor.messages.Exit

case class ClearAuth
case class SetAuth( username:String, password:String )
case class GetAuth

class AuthorizationActor extends Actor {
  
  private val encoder = new BASE64Encoder()
  private var authToken: Option[String] = None
  
  private def createAuthToken( username: String, password: String ) =
    Option( "Basic " + encoder.encode( ( username + ':' + password ).getBytes() ) )
    
  def act() {
    loop {
      react {
        case ClearAuth => authToken = None
        case SetAuth( username, password ) => authToken = createAuthToken( username, password )
        case GetAuth => reply( authToken )
        case Exit => exit()
        case _ => throw new TimeLapseException( "Invalid message" )
      }
    }
  }
}